package com.apimarket.util.net;

import com.apimarket.enums.NetContextEnum;
import com.apimarket.exception.NetContextException;
import com.apimarket.util.kong.KongOperationType;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Map;

/**
 * @Description:
 * @Author ZXR
 * @Date 2021/7/7 14:12
 * @Version 1.0
 */


public class NewPatchJsonNetContext extends PatchJsonNetContext {
    public NewPatchJsonNetContext(String url, Map<String, Object> params) {
        super(url, params);
    }

    public JsonNode getResultJsonByOperationType(String operationType) throws IOException, URISyntaxException {
        try (CloseableHttpResponse response = getResponse()) {
            int statusCode = response.getStatusLine().getStatusCode();
            HttpEntity entity = response.getEntity();
            String jsonStr = getJsonStr(entity);
            EntityUtils.consume(entity);
            if (statusCode == super.SUCCESS_CODE) {
                return new ObjectMapper().readTree(jsonStr);
            } else {
                logger.error(jsonStr);
                if(jsonStr.contains("\"name\":\"unique constraint violation\"")){
                    //如果包含这句话
                    switch(operationType){
                        case KongOperationType.ROUTE_UPDATE:
                            throw new NetContextException(NetContextEnum.ROUTE_UNIQUE_ERROR);

                    }
                }
                throw new NetContextException(NetContextEnum.UPDATE_ERROR);
            }

        }
    }
}
